package com.xyd.Filter;


import com.xyd.Entity.ManageUser;
import com.xyd.Entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/html/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path =request.getServletPath();
        if(path!=null&&!(
                path.endsWith("html") ||
                path.endsWith("htm") ||
                path.endsWith("jpg") ||
                path.endsWith("jpeg") ||
                path.endsWith("png") ||
                path.endsWith("gif") ||
                path.endsWith("bmp") ||
                path.endsWith("ico") ||
                path.endsWith("js") ||
                path.endsWith("css") ||
                path.endsWith("avi") ||
                path.endsWith("mp4") ||
                path.endsWith("mp3") ||
                path.endsWith("mkv") ||
                path.endsWith("rm") ||
                path.endsWith("rmvb")
                )){
            System.out.println("["+path+"]\t:用户登录过滤器:");
            HttpSession session =request.getSession();
            User user = (User) session.getAttribute("user");
            ManageUser manageUser = (ManageUser) session.getAttribute("manageUser");
            if(user!=null||manageUser!=null){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
//                request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
//                return;
                response.sendRedirect("/shopping/login.jsp");
            }
        }else if (path!=null&&(
                path.endsWith("jpg") ||
                path.endsWith("jpeg") ||
                path.endsWith("png") ||
                path.endsWith("gif") ||
                path.endsWith("bmp") ||
                path.endsWith("ico") ||
                path.endsWith("js") ||
                path.endsWith("css") ||
                path.endsWith("avi") ||
                path.endsWith("mp4") ||
                path.endsWith("mp3") ||
                path.endsWith("mkv") ||
                path.endsWith("rm") ||
                path.endsWith("rmvb")
        )){
            System.out.println("["+path+"]\t:用户非登录过滤器:");
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            System.out.println("["+path+"]\t:已被登陆过滤器拦截");
        }
    }

    @Override
    public void destroy() {

    }
}


